﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.DirectoryServices.AccountManagement;

namespace Remote_Commander
{
    public partial class frm_connectToAD : Form
    {
        //Public properties, accessed by frm_MainWindow
        public string strDomainController
        {
            get;
            set;
        }
        public bool connectionSuccessful
        {
            get;
            set;
        }

        public PrincipalContext ActiveDirectoryConnection
        {
            get;
            set;
        }

        public frm_connectToAD()
        {
            InitializeComponent();

            //Load the previously used domain controller, if there is one
            if (Properties.Settings.Default.LastDomainController != string.Empty)
            {

                txt_DomainController.Text = Properties.Settings.Default.LastDomainController;
            }
        }

        private void btn_connectToAD_Click(object sender, System.EventArgs e)
        {
            //Validate the text field
            if (txt_DomainController.Text == string.Empty)
            {
                MessageBox.Show("You must enter a valid IP address or hostname.");
            }
            else
            {
                //Connect to the domain controller
                strDomainController = txt_DomainController.Text;
                try
                {
                    //Create a new connection
                    ActiveDirectoryConnection = new PrincipalContext(ContextType.Domain, strDomainController);

                    connectionSuccessful = true;
                    
                    //Save the domain controller name
                    Properties.Settings.Default.LastDomainController = txt_DomainController.Text;
                    Properties.Settings.Default.Save();

                    this.Close();
                }
                catch (Exception ex)
                {
                    //Could not connect
                    MessageBox.Show("Error: " + ex.Message);
                }
            }
        }
    }
}
